﻿<%@ webhandler Language="C#" class="FsdFileManager" %>

using System;
using System.Text;
using System.Collections;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using LitJson;
using System.Collections.Generic;
using System.Web.SessionState;//第一步：导入此命名空间

public class FsdFileManager : IHttpHandler, IRequiresSessionState
{
	public void ProcessRequest(HttpContext context)
	{
        string path = context.Request.ApplicationPath;
        string basePath = context.Request.Url.Scheme + "://" + context.Request.Url.Host + ":" + context.Request.Url.Port + path + "/";
        string root = HttpRuntime.AppDomainAppPath.ToString();
        
        
        string qtrootpath = context.Request.QueryString["qtrootpath"];

        string operatType = context.Request.QueryString["operattype"];//当前操作方式（1.显示 2.删除 3.新建文件夹 4.上传）
        string url = "";
        string oldurl = "";
        if (!operatType.Equals("4"))
        {
            if (context.Request.QueryString["qtrootpath"] != null && !context.Request.QueryString["qtrootpath"].Equals(""))
            {
                url = context.Request.QueryString["qtrootpath"];
            }
            else
            {
                if (context.Session["imgpath"] == null)
                {
                    Hashtable result = new Hashtable();
                    result["message"] = "请重新登陆！";
                    context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
                    context.Response.Write(JsonMapper.ToJson(result));
                    context.Response.End();
                    return;

                }
                url = context.Session["imgpath"].ToString() + "/";
            }



            if (url != null && !url.Equals(""))
            {
                oldurl = url;
            }
        }
        
        if (operatType != null && !operatType.Equals("") && operatType.Equals("1"))
        {
            string[] fileTypes = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp", ".swf", ".doc", ".xls", ".docx", ".xlsx", ".rar" };//图片扩展名
            string showtype = context.Request.QueryString["showtype"];//显示方式
            string nowpath = context.Request.QueryString["nowpath"];//当前路径
            string previouspath = "";//上一级路劲
            if (nowpath != null && !nowpath.Equals("") && !nowpath.Equals(url))
            {
                string[] split = nowpath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < split.Length; i++)
                {
                    if (i != (split.Length - 1))
                    {
                        sb.Append(split[i] + "/");

                    }
                }
                previouspath = sb.ToString();
                url = nowpath;
            }
            if (!Directory.Exists(root + url))
            {
                context.Response.Write("指定路径错误！");
                context.Response.End();
            }
            else {
                Hashtable result = new Hashtable();
                List<Hashtable> dirFileList = new List<Hashtable>();
                result["filelist"] = dirFileList;
                //遍历目录取得文件信息
                string[] dirList = Directory.GetDirectories(root + url);
                string[] fileList = Directory.GetFiles(root + url);
                for (int i = 0; i < dirList.Length; i++)
                {
                    DirectoryInfo dir = new DirectoryInfo(dirList[i]);
                    Hashtable hash = new Hashtable();
                    hash["filetype"] = "1";
                    hash["filename"] = dir.Name;
                    hash["filesize"] = 0;
                    hash["filepath"] = url;
                    hash["shortfilepath"] = url.Replace(oldurl, "");
                    hash["imagepath"] = basePath + "FsdFileManager/skins/me/img/folder-64.gif";
                    hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                    dirFileList.Add(hash);
                }
                for (int i = 0; i < fileList.Length; i++)
                {
                    FileInfo file = new FileInfo(fileList[i]);
                    Hashtable hash = new Hashtable();
                    string sname = file.Extension;
                    for (int j = 0; j < fileTypes.Length; j++ ) 
                    {
                        if (sname.Equals(fileTypes[j]))
                        {
                            hash["filetype"] = "2";
                            hash["filename"] = file.Name;
                            hash["filesize"] = file.Length;
                            hash["filepath"] = url + file.Name;
                            hash["shortfilepath"] = (url + file.Name).Replace(oldurl, "");
                            if(showtype.Equals("1"))
                            {
                                hash["imagepath"] = basePath + url + file.Name;
                            }
                            else if(showtype.Equals("2"))
                            {
                                hash["imagepath"] = basePath + "FsdFileManager/skins/me/img/file-16.gif";
                            }
                            hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                            dirFileList.Add(hash);
                        }
                    }
                }
                context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
                result["rootpath"] = url;
                result["previouspath"] = previouspath;
                context.Response.Write(JsonMapper.ToJson(result));
                context.Response.End();
            }
        }
        else if (operatType != null && !operatType.Equals("") && operatType.Equals("2"))
        {
            string deletepath = root + context.Request.QueryString["nowpath"];
            DirectoryInfo directory = new DirectoryInfo(deletepath);
            Hashtable result = new Hashtable();
            if(directory.Exists){
                if (directory.GetDirectories().Length > 0 || directory.GetFiles().Length > 0)
                {
                    result["result"] = "error";
                    result["message"] = "该目录不为空，不能直接是删除！";
                }
                else 
                {
                    directory.Delete();
                    result["result"] = "success";
                    result["message"] = "删除成功，请重新登录！";
                }
            }else{
                FileInfo file = new FileInfo(deletepath);
                if (file.Exists)
                {
                    file.Delete();
                    result["result"] = "success";
                    result["message"] = "删除成功，请重新登录！";
                }
            }
            context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(result));
            context.Response.End();
        }
        else if (operatType != null && !operatType.Equals("") && operatType.Equals("3")) 
        {
            //新建文件夹
            Hashtable result = new Hashtable();
            string nowpath = context.Request.QueryString["nowpath"];
            string rootpath = context.Request.QueryString["rootpath"];
            string newfolder = context.Request.QueryString["newfolder"];
            newfolder = context.Server.UrlDecode(newfolder);

            if (nowpath == null || nowpath.Equals(""))
            {
                if (rootpath != null && !rootpath.Equals(""))
                {
                    nowpath = rootpath;

                }
                else
                {
                    result["result"] = "success";
                    result["message"] = "路径错误！";
                }
            }

            string newname = DataProcessing.Public.Chinese2Spell.GetFirstPinYin(newfolder.Trim());
            string fullpathh = root + nowpath + newname;
            if (Directory.Exists(fullpathh))
            {
                result["result"] = "error";
                result["message"] = "该目录已存在！";
            }
            else 
            {
                Directory.CreateDirectory(fullpathh);
                result["result"] = "success";
                result["message"] = "目录创建成功！";
            }

            context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(result));
            context.Response.End();
        }
	}
    
    private void showError(string message, HttpContext context)
    {
        Hashtable hash = new Hashtable();
        hash["error"] = 1;
        hash["message"] = message;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }
    
	public bool IsReusable
	{
		get
		{
			return true;
		}
	}
}

